<?php

namespace App\Http\Controllers\V1\BasicData;

use App\Http\Requests\V1\ToolsIdentityRequest;
use App\Models\V1\ApplyPays;
use App\Models\V1\Custodians;
use App\Models\V1\NewStudent;
use App\Models\V1\ReceiveStatus;
use App\Models\V1\ResultClasses;
use App\Models\V1\ResultDorms;
use App\Models\V1\ResultMajors;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ToolsKeyController extends Controller
{
    /**
     * 显示宿舍钥匙发放数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('v1.tools.key');
    }

    /**
     * 获取宿舍钥匙发放数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];
        // 获取符合查询条件的年级数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('keywords');

        // 获取符合查询条件的年级数据
        $data = $this->getWaitKeyList($currentPage, $rows, $keywords);


        if (!$data->isEmpty()) {
            $formatList = array();
            $count = $data->total() > 0 ? $data->total() : 0;
            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $formatItem['exam_code'] = $item['exam_code'];
                    $student = $this->getNewStudentByCode($item['exam_code']);
                    $formatItem['enrollment_numbering'] = $student['enrollment_numbering'];
                    $formatItem['name'] = $student['name'];
                    $formatItem['sex'] = $this->formatStudentSex($student['sex']);
                    $formatItem['card_type'] = $student['card_type'];
                    $formatItem['card_number'] = $student['card_number'];
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }
                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }

        return $response;
    }

    /**
     * 进入单条宿舍钥匙发放数据显示界面（适用于查看viewData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $data['view'] = $request->input('view');
        switch ($request->input('view')) {
            case 'viewData':
                $data['exam_code'] = $request->input('code');
                $exam_code = $data['exam_code'];
                $currentStudent = $this->getNewStudentByCode($exam_code);
                $currentStudent['sex'] = $this->formatStudentSex($currentStudent['sex']);
                $currentStudent['is_dorm'] = $this->getIsDorm($exam_code);
                $currentStudent['is_pay'] = $this->getIsPay($exam_code);
                $currentStudent['is_report'] = $this->getIsRegister($exam_code);
//                2.生活用品发放 3.教材发放 4.校服发放 5.宿舍钥匙发放
                $currentStudent['is_daily_use'] = $this->getIsReceive($exam_code,2);
                $currentStudent['is_textbook'] = $this->getIsReceive($exam_code,3);
                $currentStudent['is_cloth'] = $this->getIsReceive($exam_code,4);
                $currentStudent['is_key'] = $this->getIsReceive($exam_code,5);
                $currentStudent['admission_major'] = $this->getAdmissionMajor($exam_code);
                $history = $currentStudent['medical_history'];
                if (empty($history) || !isset($history)) {
                    $history='';
                }else{
                    $historyArr = explode('--',$history);
                    if (count($historyArr) == 2){
                        if (!empty($historyArr[0])) {
                            $history = $historyArr[0].','.$historyArr[1];
                        }else{
                            $history = $historyArr[1];
                        }
                    }elseif (count($historyArr) == 1) {
                        $history = $historyArr[0];
                    }else {
                        $history = '';
                    }
                }
                $currentStudent['medical_history'] = $history;

                //学生班级
                $currentStudent['class_name'] = $this->getStudentClass($exam_code);

                //学生宿舍
                $currentStudent['dorm_name'] = $this->getStudentDorm($exam_code);

                //监护人
                $currentStudent['custodian'] = $this->getNewStudentCustodianByCode($exam_code);

                $data['itemData'] = $currentStudent;
                return view('v1.form.new_student_item', $data);
                break;
            case 'showQRCode':
                return view('v1.tools.key_item', $data);
                break;
        }
    }

    /**
     * 确认学生身份信息
     *
     * @param ToolsIdentityRequest $request
     * @return array
     */
    public function sureData(ToolsIdentityRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '考试号[' . $request->input('code') . '],宿舍钥匙发放失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateIdentity($request);

            // 删除年级信息
            $successFlag = $this->handleSure($request);
            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '考试号[' . $request->input('code') . '],宿舍钥匙发放成功！';
            }
        }

        return $response;
    }

    /**
     * 删除宿舍钥匙发放基本信息
     *
     * @param TermRequest $request
     * @return array
     */
    public function deleteData(ToolsIdentityRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '考试号[' . $request->input('code') . '],删除失败！',
        ];
        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateIdentity($request);
            // 删除年级信息
            $successFlag = $this->handleDelete($request);
            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '考试号[' . $request->input('code') . '],删除成功！';
            }
        }

        return $response;
    }


    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的宿舍钥匙发放列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getWaitKeyList($page = 1, $rows, $keywords)
    {
        if (!isset($keywords) || empty($keywords)) {
            $data = ReceiveStatus::where(['type'=>5,'status'=>false])
                ->orderBy('created_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page);
        } else {
            $data = ReceiveStatus::where(['type'=>5,'status'=>false])
                ->where('exam_code', 'like', '%' . $keywords . '%')
                ->orderBy('created_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page);
        }
        return $data;
    }


    /***
     * 根据学生考试号获取学生详细信息
     * @param $code
     * @return mixed
     */
    private function getNewStudentByCode($code)
    {
        $student = NewStudent::where('exam_code', $code)->first();
        return $student;
    }

    /***
     * 获取学生监护人
     * @param $code
     * @return mixed
     */
    private function getNewStudentCustodianByCode($code)
    {
        $student = Custodians::where('exam_code', $code)->get();
        return $student;
    }


    /***
     * 根据学生代码判断是否住宿
     * @return array
     */
    private function getIsDorm($code)
    {
        $dorm = ResultDorms::where('exam_code',$code)->first();
        if (!empty($dorm) || isset($dorm)) {
            return '是';
        }
        return '否';

    }

    /***
     * 检测是否已报到
     * @param $code
     * @return mixed
     */
    private function getIsRegister($code)
    {

        $is_register = ReceiveStatus::where(['exam_code'=>$code,'type'=>5,'status'=>true])
            ->first();
        if (!empty($is_register) || isset($is_register)) {
            return '是';
        }
        return '否';
    }


    /***
     * 1:报到 2.生活用品发放 3.教材发放 4.校服发放 5.宿舍钥匙发放
     * 获取物品领取状态
     * @param $code
     * @return string
     */
    private function getIsReceive($code, $type)
    {
        $is_register = ReceiveStatus::where(['exam_code'=>$code,'type'=>$type,'status'=>true])
            ->first();
        if (!empty($is_register) || isset($is_register)) {
            return '是';
        }
        return '否';
    }

    /***
     * 检测是否缴费
     * @param $code
     * @return mixed
     */
    private function getIsPay($code)
    {
        $pay = ApplyPays::where(['exam_code'=>$code,'status'=>true])->first();
        if (!empty($pay) || isset($pay)) {
            return '是';
        }
        return '否';
    }

    /***
     * 获取学生分配班级
     * @param $code
     * @return string
     */
    private function getStudentClass($code)
    {
        $class_name = '';
        $stu_class = ResultClasses::where('exam_code', $code)
            ->first();
        if (!empty($stu_class) || isset($stu_class)) {
            $class_name = $stu_class->name;
        }else {
            $class_name = '未分配';
        }
        return $class_name;
    }

    /***
     * 获取学生分配宿舍
     * @param $code
     * @return string
     */
    private function getStudentDorm($code)
    {
        $dorm_name = '';
        $is_dorm = $this->getIsDorm($code);
        if ($is_dorm === '否'){
            $dorm_name = '学生不住宿';
        }else {
            $stu_dorm = ResultDorms::where('exam_code', $code)
                ->first();
            if (!empty($stu_dorm) || isset($stu_dorm)) {
                $dorm_name = $stu_dorm->building.$stu_dorm->floor.$stu_dorm->dorm_code;
            }else{
                $dorm_name = '未分配';
            }
        }
        return $dorm_name;
    }


    /***
     * 获取学生录取专业
     * @param $code
     */
    public function getAdmissionMajor($code) {
        $major = ResultMajors::where('exam_code',$code)->first();
        if (empty($major)) {
            return '';
        }else {
            return $major->name;
        }
    }


    ///////////////////////////////////////////////////////////////////
    /// 验证表单功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新宿舍钥匙发放信息验证请求
     *
     * @param TermRequest $request
     */
    private function validateIdentity(ToolsIdentityRequest $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑处理功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理确认身份信息
     *
     * @param Request $request
     * @return bool
     */
    private function handleSure(Request $request) {
        $exam_code = $request->input('code');
        // 拼装更新数据数组
        $updateData = [
            'status' => true,
        ];
        $rspObj = ReceiveStatus::where(['exam_code'=>$exam_code,'type'=>5])->update($updateData);
        return $rspObj;
    }

    /**
     * 处理删除宿舍钥匙发放信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request)
    {
        $exam_code = $request->input('code');
        $rspObj = ReceiveStatus::where(['exam_code'=>$exam_code,'type'=>5])->delete();
        return $rspObj;
    }

    /***
     * 检测是否缴费
     * @param $code
     * @return mixed
     */
    private function formatStudentSex($val)
    {
        if ($val == 1) {
            return '男';
        } elseif ($val == 2) {
            return '女';
        } else {
            return '';
        }
    }
}
